package com.qianxing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianxing.convert.UserInfoMapper;
import com.qianxing.dto.UserInfoDTO;
import com.qianxing.exceptionhandler.EnumException;
import com.qianxing.exceptionhandler.ResponseException;
import com.qianxing.po.TbUserInfoPO;
import com.qianxing.service.TbUserInfoService;
import com.qianxing.mapper.TbUserInfoMapper;
import com.qianxing.vo.UserInfoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import static com.qianxing.utils.RedisContanct.LOGIN_USER_KEY;

/**
 * @author JasonLong
 * @description 针对表【tb_user_info(用户信息表)】的数据库操作Service实现
 * @createDate 2023-07-06 11:34:44
 */
@Service
public class TbUserInfoServiceImpl extends ServiceImpl<TbUserInfoMapper, TbUserInfoPO>
        implements TbUserInfoService {

    private Logger LOGGER = LoggerFactory.getLogger(TbUserInfoServiceImpl.class);

    @Autowired
    private TbUserInfoMapper userInfoMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Boolean saveUserInfo(UserInfoDTO userInfoDTO) {
        TbUserInfoPO tbUserInfoPO = UserInfoMapper.INSTANCE.DTOToPO(userInfoDTO);
        System.out.println();
        System.out.println(tbUserInfoPO);
        boolean save = save(tbUserInfoPO);
        return save;
    }

    public ResponseException getUserOpenId(String OpenId) {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("user_openid", OpenId);
        TbUserInfoPO one = getOne(wrapper);
        return ResponseException.success(one);
    }

    @Override
    public UserInfoVO getUser(String token) {
        Long expire = stringRedisTemplate.opsForValue().getOperations().getExpire(LOGIN_USER_KEY + token);
        //如果token已过时
        if (expire < 0) {
            return null;
        }
        String userOpenId = stringRedisTemplate.opsForValue().get(LOGIN_USER_KEY + token);

        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("user_openid", userOpenId);

        TbUserInfoPO one = getOne(wrapper);
        UserInfoVO userInfoVO = UserInfoMapper.INSTANCE.POtoVO(one);
        LOGGER.info("===TOKEN IS VILAD===");
        return userInfoVO;
    }
}